package groupchat.server;

import java.util.*;

import com.alibaba.fastjson.JSONObject;
import groupchat.entities.ClientMessage;
import groupchat.entities.ServerMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

//测试，这个部分提交
public class ServerHandler extends SimpleChannelInboundHandler<String> {
    //群发
    public static final int RADIO = 1;
    //私发
    public static final int ALONE = 2;
    //保存用户名映射channel
    private static Map<String,Channel> channels = new HashMap<>();
    private static Map<Channel,String> names = new HashMap<>();

    //获得发送方的信息
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        //获得发送方的channel
        Channel sender = ctx.channel();
        //将msg进行解析
        ClientMessage clientMessage = JSONObject.parseObject(msg, ClientMessage.class);
        //获得发送者名称
        String senderName = clientMessage.getSender();
        //注册部分
        if(!channels.containsKey(senderName)) { //未注册（则先将自己注册）
            channels.put(senderName,sender);
            names.put(sender,senderName);
        }

        if (clientMessage.getType() == RADIO) { //判断为群发
            Set<Channel> channelSet = names.keySet();
            for(Channel channel : channelSet) {
                //获得接收者名称
                String receiverName = names.get(channel);
                channel.writeAndFlush(JSONObject.toJSONString(new ServerMessage(senderName,receiverName, clientMessage.getText())));
            }
        }else { //私发
            String receiverName = clientMessage.getReceiver();
            //获得私发对象的channel
            Channel receiver = channels.get(receiverName);
            receiver.writeAndFlush(JSONObject.toJSONString(new ServerMessage(senderName,receiverName,clientMessage.getText())));
        }
    }

    //退出群聊，则移出缓存
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //获得退出者channel
        Channel outer = ctx.channel();
        //获得退出者姓名
        String name = names.get(outer);
        //移出缓存
        names.remove(outer);
        channels.remove(name);
        System.err.println(name + "退出群聊");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    }
}
